package top.likeqc.blog.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.likeqc.blog.NotFoundException;
import top.likeqc.blog.dao.TagRepository;
import top.likeqc.blog.pojo.Tag;
import top.likeqc.blog.service.TagService;

import java.util.Optional;

/**
 * @author likeqc.top
 * @date 2021/4/17 8:39
 */
@Service
@Transactional
public class TagServiceImpl implements TagService {

    @Autowired private TagRepository tagRepository;

    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }

    @Override
    public Tag updateTag(Long id, Tag tag) {
        Optional<Tag> result = tagRepository.findById(id);
        if (!result.isPresent()) {
            throw new NotFoundException("不存在该标签");
        }
        Tag tag1 = result.get();
        BeanUtils.copyProperties(tag, tag1);
        return tagRepository.save(tag1);
    }

    @Override
    public Tag getTag(Long id) {
        return tagRepository.findById(id).get();
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }
}
